import editForm from "../form.vue";
import { message } from "@/utils/message";
import { handel_rule_info, handel_rule_save } from "@/api/index";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h, computed } from "vue";
import type { FormItemProps } from "./types";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";

import { useUserStoreHook } from "@/store/modules/user";

export function useRole() {
  /** 页面元素权限 */
  const auth_element = computed(() => {
    return useUserStoreHook()?.auth_element;
  });

  const permissions = reactive({
    is_dataRule_set: false, // 设置
  })

  // 数据
  const dataForm = ref(null);

  function handleOffline(row) {
    message(`${row.username}已被强制下线`, { type: "success" });
    onSearch();
  }

  async function onSearch() {
    const { data } = await handel_rule_info();
    dataForm.value = {
      gain_limt: data.gain_limt,
      lock_limit: data.lock_limit,
      silent_day: data.silent_day,
      valid_day: data.valid_day,
      sea_limit: data.sea_limit
    }
  }
  
  // 表单
  const formRef = ref();
  function openDialog(form?: FormItemProps) {
    addDialog({
      title: "数据处理规则设置",
      props: {
        formInline: {
          gain_limt: form?.gain_limt ?? 0,
          lock_limit: form?.lock_limit ?? 0,
          silent_day: form?.silent_day ?? 0,
          valid_day: form?.valid_day ?? 0,
          sea_limit: form?.sea_limit ?? 0
        }
      },
      width: "500px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`设置成功！`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(valid => {
          if (valid) {
            handel_rule_save(curData).then(res => {
              if (res.code == 1000) {
                chores();
              } else {
                message(res.msg, { type: "error" });
              }
            });
          }
        });
      }
    });
  }

  onMounted(() => {
    onSearch();

    /** 筛选完-页面元素权限 */
    if (auth_element.value) {
      // 查询 onpage 为 "/customerManagement/rules/index" 的所有数据
      const homeData = Object.entries(JSON.parse(auth_element.value)).filter(([key, value]) => value.onpage === "/customerManagement/rules/index");
      // 转换为对象形式
      const homeDataObj: any = Object.fromEntries(homeData);
      
      // dataRule_set
      if (homeDataObj.dataRule_set) permissions.is_dataRule_set = true
    }
  });

  return {
    permissions,
    
    dataForm,
    handleOffline,
    openDialog
  };
}
